import * as CryptoJS from 'crypto-js';
import { SafeUrl, DomSanitizer } from '@angular/platform-browser';
declare var _: any;

export function parseDateStr(str) {
  const separator = '-';
  const dateArr = str.split(separator);
  const year = parseInt(dateArr[0]);
  let month;
  // 处理月份为04这样的情况
  if (dateArr[1].indexOf('0') === 0) {
    month = parseInt(dateArr[1].substring(1));
  } else {
    month = parseInt(dateArr[1]);
  }
  const day = parseInt(dateArr[2]);
  const date = new Date(year, month - 1, day);
  return date;
}

export function getQueryString(url, paraName) {
  const arrObj = url.split('?');
  if (arrObj.length > 1) {
    const arrPara = arrObj[1].split('&');
    let arr;
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=');
      // eslint-disable-next-line eqeqeq
      if (arr != null && arr[0] === paraName) {
        return arr[1];
      }
    }
    return '';
  } else {
    return '';
  }
}

export const openWindow = (url, title, w, h) => {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft = window.screenLeft;
  const dualScreenTop = window.screenTop;

  const width = window.innerWidth
    ? window.innerWidth
    : document.documentElement.clientWidth
    ? document.documentElement.clientWidth
    : screen.width;
  const height = window.innerHeight
    ? window.innerHeight
    : document.documentElement.clientHeight
    ? document.documentElement.clientHeight
    : screen.height;

  const left = width / 2 - w / 2 + dualScreenLeft;
  const top = height / 2 - h / 2 + dualScreenTop;
  const newWindow = window.open(
    url,
    title,
    'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' +
      w +
      ', height=' +
      h +
      ', top=' +
      top +
      ', left=' +
      left,
  );

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus();
  }
};

/**
 * 生成blob对象
 */
export const handleImg = (http, sanitizer: DomSanitizer, fileName, fn: (url: SafeUrl) => void) => {
  http.request('get', `/cf/admin/sysfile/f/${fileName}`, { responseType: 'blob' }).subscribe(file => {
    const blob = file as any;
    fn(sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(blob)));
    setTimeout(() => {
      URL.revokeObjectURL(blob);
    }, 0);
  });
};

export const replaceKeysDeep = (obj, keysMap) => {
  // keysMap = { oldKey1: newKey1, oldKey2: newKey2, etc...
  return _.transform(obj, function(result, value, key) {
    // transform to a new object

    const currentKey = keysMap[key] || key; // if the key is in keysMap use the replacement, if not use the original key

    result[currentKey] = _.isObject(value) ? replaceKeysDeep(value, keysMap) : value; // if the key is an object run it through the inner function - replaceKeys
  });
};

/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date = false) => {
  let random = '';
  random = Math.ceil(Math.random() * 100000000000000)
    .toString()
    .substr(0, len || 4);
  if (date) random = random + Date.now();
  return random;
};

export const encryption = params => {
  let { data, type, param, key } = params;
  const result = JSON.parse(JSON.stringify(data));
  if (type === 'Base64') {
    param.forEach(ele => {
      result[ele] = btoa(result[ele]);
    });
  } else {
    param.forEach(ele => {
      const data = result[ele];
      key = CryptoJS.enc.Latin1.parse(key);
      const iv = key;
      // 加密
      const encrypted = CryptoJS.AES.encrypt(data, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding,
      });
      result[ele] = encrypted.toString();
    });
  }
  return result;
};
